#coding=utf-8
import httplib2,os,datetime,time,pickle
from stockdb.misc import *
from stconfig import tut_fn

class CodesCache(object):
    def __init__(self, fn=tut_fn): 
        self.fn = fn
        self.codes = []
        self._load_codes()
        
    def _load_codes(self):
        self.codes = pickle.load(open(self.fn))
     
    def _dump_codes(self): 
        pickle.dump(self.codes, open(self.fn, 'w'))
    
    def get(self):
        self._load_codes()
        return self.codes
    
    def append(self, cs):
        if type(cs) == type([]):
            self.codes.extend(cs)
        else:
            self.codes.append(cs)
            
        self.codes = list( set(self.codes) )   
        self._dump_codes() 
    
    def remove(self, code):
        self.codes.remove(code)
        self._dump_codes()
cc = CodesCache()
        
def add2fav(codes):
    fn = '/home/jay/.psq/config'

    sent = []
    for c in codes:
        s = find_stock(c)
        
        a = '%s%s,'%(s.market, s.code)
        b = '%s'%s.name
        sent.append(a+b)
        
    sent = ';'.join(sent)

    f = open(fn, 'w')
    f.write('[group]\n')
    sent = 'favorit = ' + sent
    f.write(sent)

    f.close()

img_type_list=[("min","分钟"),("daily","日K"),("weekly","周K"),("monthly","月K"),("macd","MACD"),("kdj","KDJ"),("wr","W&R")]

def add2fav2(codes):
    pass
    
def get_sina_kimg(code, img_type='daily', path='/home/jay/kimg'):
    
    s = find_stock(code)
    mname = '%s%s'%(s.market, code) 
    url = "http://image.sinajs.cn/newchart/%s/n/%s.gif" % (img_type,mname)
    
    fn = '%s_%s_%s.gif'%(code, img_type, datetime.datetime.now().isoformat())
    fn = os.path.join(path, fn)
    
    import socket
    socket.setdefaulttimeout(10)
    h = httplib2.Http(".cache")
    resp, content = h.request(url, "GET")
    open(fn, 'w').write(content)
    time.sleep(0.2)

if __name__ ==  '__main__':
    cs = cc.get()
    add2fav(cs)
